import 'package:get/get.dart';
import 'package:kkhousekeep/net/home_order_connect.dart';
import 'package:kkhousekeep/page/home/convenient/order/order_pending_list_page.dart';
import 'package:kkhousekeep/page/home/convenient/order/order_processed_list_page.dart';
import 'package:kkhousekeep/page/home/convenient/order/order_processing_list_page.dart';
import 'package:kkhousekeep/page/home/convenient/order/order_in_hand_list_page.dart';

import '../../../../models/order_count_entity.dart';
import '../repair/repair_home_controller.dart';

class WorkOrderController extends GetxController {
  var tabs = [
    TabModel(0, "我的工单"),
    TabModel(1, "已转单"),
  ];

  var tabViewItems = [
    TabModel(OrderState.pending.index, '待处理'),
    TabModel(OrderState.processing.index, '处理中'),
    TabModel(OrderState.hanging.index, '挂单中'),
    TabModel(OrderState.processed.index, '已处理'),
  ];

  var tabId = 0.obs;

  var selfCountEntity = OrderCountObj()
      .copyWith(
        pending: 0,
        processing: 0,
        hanging: 0,
        processed: 0,
      )
      .obs;

  var transferredCountEntity = OrderCountObj()
      .copyWith(
        pending: 0,
        processing: 0,
        hanging: 0,
        processed: 0,
      )
      .obs;

  late HomeOrderConnect _connect;

  @override
  void onInit() {
    _connect = Get.put(HomeOrderConnect());
    _loadNetworkData();
    super.onInit();
  }

  void performClickTab({
    required int tabId,
  }) {
    if (this.tabId.value == tabId) {
      return;
    }
    this.tabId.value = tabId;
    _loadNetworkData();
  }

  void performClick(TabModel model) {
    bool isFromMyWorkOrder = tabId.value == tabs[0].id;
    OrderState orderState = OrderState.values[model.id];

    ///待处理
    if (OrderState.pending == orderState) {
      Get.to(() => OrderInHandListPage(isFromMyWorkOrder: isFromMyWorkOrder))?.whenComplete(() => _loadNetworkData());
      return;
    }

    ///处理中
    if (OrderState.processing == orderState) {
      Get.to(OrderProcessingListPage(isFromMyWorkOrder: isFromMyWorkOrder))?.whenComplete(() => _loadNetworkData());
      return;
    }

    ///挂单中
    if (OrderState.hanging == orderState) {
      Get.to(OrderPendingListPage(isFromMyWorkOrder: isFromMyWorkOrder))?.whenComplete(() => _loadNetworkData());
      return;
    }

    ///已处理
    if (OrderState.processed == orderState) {
      Get.to(OrderProcessedListPage(isFromMyWorkOrder: isFromMyWorkOrder))?.whenComplete(() => _loadNetworkData());
      return;
    }
  }

  void _loadNetworkData() async {
    OrderCountObj entity = await _connect.getOrderCount(type: tabId.value);
    if (tabId.value == tabs[0].id) {
      selfCountEntity.value = entity;
      return;
    }
    transferredCountEntity.value = entity;
  }
}

enum OrderState {
  pending,
  processing,
  hanging,
  processed,
}
